package com.笔试题;

import java.util.Arrays;

/**
 * 合并两个有序数组
 * 从两个长度为N的数组中找到第N个数和第N+1个数
 * @author qiuxiaochen
 *
 */
public class 双有序数组取第N个数 {

	//两个有序数组的合并操作
	public static int[] merge(int a[], int b[]) {
		if (a == null || a.length == 0)
			return b;
		if (b == null || b.length == 0)
			return a;
		int result[] = new int[a.length + b.length];
		int i = 0;
		int j = 0;
		int index = 0;
		while (i < a.length && j < b.length) {
			if (a[i] <= b[j]) {
				result[index] = a[i];
				i++;
				index++;
			}else{
				result[index] = b[j];
				j++;
				index++;
			}
		}
		if(i<a.length){
			for (int k = i; k < a.length; k++) {
				result[index]=a[k];
				index++;
			}
		}
		if(j<b.length){
			for (int k = j; k < b.length; k++) {
				result[index]=b[k];
				index++;
			}
		}
		return result;
	}

	public static void main(String[] args) {
		int N=13;
		int a[]={1,2,3,5,6,7,14,26,34,56,78,99,1000};
		int b[]={3,3,4,4,8,9,10,11,12,23,45,67,1999};
		int result[]=merge(a, b);
		System.out.println(Arrays.toString(result));
		System.out.println("第"+N+"个数为:"+result[N-1]);
		System.out.println("第"+(N+1)+"个数为:"+result[N]);
	}
}
